package com.imay.live.helper;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.imay.base.helper.ActivityHelper;
import com.imay.live.IMApplication;
import com.imay.live.R;
import com.imay.live.activity.MainActivity2;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.ToastUtil;
import com.umeng.socialize.bean.SHARE_MEDIA;

/**
 * 使用全局弹窗，点击 或者离开APP 都取消弹窗
 * Created by lzx on 2017/06/26 0026.
 */

public class ShareNoticeHelper implements View.OnClickListener {
    private static Object o = new Object();
    private float temp;
    private float ty;
    private WindowManager wm;
    private View v;
    private int status;
    private long duration = 800;
    private long delayed = 5100;
    private long cancledelayed = 0;//处理没回调的情况
    boolean ishideing = false;
    private WindowManager.LayoutParams params;
    // 链接
    private String shareLink;

    // 标题
    private String title;

    // 图片文件
    private String img;
    // 描述
    private String des;

    private static ShareNoticeHelper shareNotice;

    private ShareNoticeHelper() {
    }

    public synchronized static ShareNoticeHelper getInstance() {
        if (shareNotice == null) {
            synchronized (o) {
                shareNotice = new ShareNoticeHelper();
            }
        }
        return shareNotice;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0 && v != null) {
                ishideing = true;
                temp = 0;
                if (v.getY() < 0) {
                    return;
                }
                ValueAnimator animator = new ValueAnimator();
                animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        float value = (float) animation.getAnimatedValue();
                        if (temp != value) {
                            temp = value;
                            if (temp <= -params.height) {
                                try {
                                    wm.removeView(v);
                                } catch (Exception e) {
                                }
                                shareNotice = null;
                                ishideing = false;
                            } else {
                                v.setTranslationY(value);
                            }
                        }
                    }
                });
                animator.setDuration(duration);
                animator.setFloatValues(v.getY(), -params.height);
                animator.start();

            }
        }
    };

    public synchronized void show(String shareLink, String img, String title, String des) {
        final Context context = IMApplication.getInstance();
        if (context == null) {
            return;
        }
        if (this.shareLink != null) {
            if (this.shareLink.equals(shareLink)) {
                return;
            }
        }
        this.shareLink = shareLink;
        this.title = title;
        this.img = img;
        this.des = des;
        temp = 0;
        v = LayoutInflater.from(context).inflate(R.layout.share_layout, null);
        params = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_TOAST,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
        params.flags = params.flags | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        params.flags = params.flags | WindowManager.LayoutParams.FLAG_FULLSCREEN;
        params.alpha = 1.0f;
        params.gravity = Gravity.TOP;
        status = AppUtil.getStatusBarHeight(context);
        params.height = (int) (context.getResources().getDimension(R.dimen.share_notiecH) + status);
        TextView titileview = (TextView) v.findViewById(R.id.title);
        if (titileview != null) {
            SpannableString spanstring = new SpannableString(context.getResources().getString(R.string.short_live_push_show));
            spanstring.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.text_23)), 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            titileview.setText(spanstring);
        }
        ImageView share_wx = (ImageView) v.findViewById(R.id.share_wx);
        ImageView share_py = (ImageView) v.findViewById(R.id.share_py);
        ImageView share_qq = (ImageView) v.findViewById(R.id.share_qq);
        ImageView share_sin = (ImageView) v.findViewById(R.id.share_sin);
        ImageView share_zone = (ImageView) v.findViewById(R.id.share_zone);
        RelativeLayout ret_bg = (RelativeLayout) v.findViewById(R.id.ret_bg);
        LinearLayout.LayoutParams retparams = (LinearLayout.LayoutParams) ret_bg.getLayoutParams();
        retparams.topMargin = status;
        ret_bg.setLayoutParams(retparams);
        v.setTranslationY(-params.height);
        share_wx.setOnClickListener(this);
        share_py.setOnClickListener(this);
        share_qq.setOnClickListener(this);
        share_sin.setOnClickListener(this);
        share_zone.setOnClickListener(this);
        v.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ty = event.getY();
                        break;
                    }
                    case MotionEvent.ACTION_MOVE: {
                        if (event.getY() - ty < -50 && !ishideing) {
                            ishideing = true;
                            handler.sendEmptyMessage(0);
                        }
                        break;
                    }

                }

                return false;
            }
        });
        try {
            wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            wm.addView(v, params);
            ValueAnimator animator = new ValueAnimator();
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    if (temp != value) {
                        temp = value;
                        v.setTranslationY(value);
                        if (temp == 0) {
                            handler.sendEmptyMessageDelayed(0, delayed);
                        }
                    }
                }
            });
            animator.setDuration(duration);
            animator.setFloatValues(-params.height, 0);
            animator.start();
        } catch (Exception e) {
        }

    }

    @Override
    public void onClick(View v) {
        handler.removeCallbacksAndMessages(null);
        Activity activity = getshareActivity();
        share(v.getId(), activity);
    }

    private void share(int id, final Activity activity) {
        switch (id) {
            case R.id.share_wx: {
                if (activity != null) {
                    MobclickAgent.onEvent(activity, "cdb_share_weixin");
                    handler.sendEmptyMessageDelayed(0, cancledelayed);
                    ThreadManager.post(ThreadManager.THREAD_UI, new Runnable() {
                        @Override
                        public void run() {
                            ShareSDKHelper.getBuilder(activity, SHARE_MEDIA.WEIXIN).share(shareLink, title, des, img);
                        }
                    });
                }
                break;
            }
            case R.id.share_py: {
                if (activity != null) {
                    MobclickAgent.onEvent(activity, "cdb_share_friend");
                    handler.sendEmptyMessageDelayed(0, cancledelayed);
                    ShareSDKHelper.getBuilder(activity, SHARE_MEDIA.WEIXIN_CIRCLE).share(shareLink, title, des, img);
                }
                break;
            }
            case R.id.share_qq: {
                if (activity != null && !activity.isFinishing()) {
                    MobclickAgent.onEvent(activity, "cdb_share_qq");
                    handler.sendEmptyMessageDelayed(0, cancledelayed);
                    ShareSDKHelper.getBuilder(activity, SHARE_MEDIA.QQ).share(shareLink, title, des, img);
                }
                break;
            }
            case R.id.share_sin: {
                if (activity != null) {
                    MobclickAgent.onEvent(activity, "cdb_share_weibo");
                    handler.sendEmptyMessageDelayed(0, cancledelayed);
                    ShareSDKHelper.getBuilder(activity, SHARE_MEDIA.SINA).share(shareLink, title, des, img);
                }
                break;
            }
            case R.id.share_zone: {
                if (activity != null) {
                    MobclickAgent.onEvent(activity, "cdb_share_qzone");
                    handler.sendEmptyMessageDelayed(0, cancledelayed);
                    ShareSDKHelper.getBuilder(activity, SHARE_MEDIA.QZONE).share(shareLink, title, des, img);
                    break;
                }
            }
        }
    }

    private Activity getshareActivity() {
        Activity activity = ActivityHelper.getInstance().getCurrentActivity(MainActivity2.class.getName());
        if (activity == null) {
            ToastUtil.show(IMApplication.getInstance(), IMApplication.getInstance().getString(R.string.str_dynamics_share_result_error));
            return null;
        }
        if (img == null) {
            ToastUtil.show(IMApplication.getInstance(), IMApplication.getInstance().getString(R.string.str_dynamics_share_result_error));
            return null;
        }
        return activity;
    }

    public void shareDelayed() {
        if (v == null) {
            shareNotice = null;
            return;
        }
        handler.removeCallbacksAndMessages(null);
        handler.sendEmptyMessageDelayed(0, cancledelayed);
    }
}
